import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import DutyWeekCenter from './components/DutyWeekCenter';
import NoticeDetails from './components/NoticeDetails';
import Logidn from '../common/compont/Logidn';
import ErrorTips from '../common/compont/ErrorTips';
import Error from '../common/compont/Error';
import { Spin, message } from 'antd';
import 'antd/dist/antd.css';
import './components/scss/index.scss';
import { getData, getData2, postData1, getQueryVariable } from "../common/js/fetch";
import '@wangeditor/editor/dist/css/style.css'
import { lgAlert } from 'lancoo-web-ui';
import 'lancoo-web-ui/dist/style.css'
import 'lg-select-modal/dist/index.css';

message.config({
  top: 100,
  duration: 2,
  maxCount: 1,
});


// sessionStorage.setItem('token', '20C7B277-0969-4B54-8B09-6723F4B8DB4A');
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      start: 0,
      sysId: '252',
      lockerId: '621',
      skin: 2,
    };
  }
  alertAInfo2 = () => {
    let alert = lgAlert.show({
      duration: 0,
      content: '您当前的身份没有访问该应用的权限，点击确定返回办公平台',
      tipType: 'info',
      tipSize: 'small',
      tipMouldType: 'A',
      isShowCloseBtn: false,
      showConfirm: false,
      closeText: "知道了",
      onCancel: () => {
        lgAlert.close(alert.index);
        this.openBaseUrl();
      }
    });
  }
  openBaseUrl = () => {
    window.open(sessionStorage.getItem('baseUrl'), '_self');
  }
  componentDidMount() {
    let token = sessionStorage.getItem('token') || getQueryVariable('lg_tk');
    console.log(window.location.href, getQueryVariable('lg_tk'), 'token')
    let isManage = getQueryVariable('isManage');
    if (isManage === '1') {
      sessionStorage.setItem('isManage', isManage);
    } else {
      sessionStorage.setItem('isManage', '2');
    }
      let isDep = getQueryVariable('isDep');
     if (isDep === '1') {
      sessionStorage.setItem('isDep', isDep);
    } else {
      sessionStorage.setItem('isDep', '2');
    }
    //用户信息获取
    getData('/api/common/user', { token: token }).then(res => res.json()).then(res => {
      if (res.code == 200 && res.data) {
        // console.log('res.data', res.data);
        let userInfo = res.data;
        if (userInfo.userType === '0' || userInfo.userType === '6' || userInfo.userType === '7' || userInfo.userType === '8') {
          userInfo.role = '管理员';
        } else {
          userInfo.role = '非管理员';
        }
        sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
        // 2023-09-14 适配高级管理员
        let identityList = userInfo.identityList;
        let identity = identityList.find(item => item.identityCode === getQueryVariable('lg_ic'))
        if (identity?.advanced == 1) {
          sessionStorage.setItem('isAdvanced', 1);
        } else {
          sessionStorage.setItem('isAdvanced', 0);
        }
        //系统信息获取
        getData('/api/common/system/info', {
          schoolId: userInfo.schoolId
        })
          .then(res => res.json())
          .then(res => {
            if (res.code == 200 && res.data) {
              let schoolData = res.data;
              console.log(res, 'res1', schoolData.baseUrl);
              sessionStorage.setItem('baseUrl', schoolData.baseUrl);
              sessionStorage.setItem('schoolSystemInfo', JSON.stringify(schoolData));
              getData2(schoolData.baseUrl + 'openapi/v1/system/facade/getSkin', {
                appid: 252,
                token,
              }).then(data => {
                return data.json()
              }).then(json => {
                let skin = json.Data.skin;
                sessionStorage.setItem('skin', skin);
                this.setState({
                  skin
                }, () => {
                  document.body.className += ` lg-skin-s${skin}`;
                })
              }).catch((e) => {
                console.log('e', e);
              })
              //验证是否已登录
              if (schoolData) {
                let script = document.createElement("script");
                script.src = schoolData.baseUrl + "/UserMgr/Login/JS/CheckIsOnline2.js";
                script.type = "text/javascript";
                script.onload = function () {
                  // 重复登录检测 2023-04-11
                  window._LgBase_initCheck(schoolData.baseUrl, token, "270");
                }
                document.getElementsByTagName("head")[0].appendChild(script);
              }
              let url = schoolData.baseUrl + '/UserMgr/PowerMgr/ValidateIdentity'
              postData1(url, {
                IdentityCode: getQueryVariable('lg_ic'),
                ModuleID: isManage === '1' ? 222001 : 222002,
                UserID: userInfo.userId
              })
                .then(res => { return res.json() })
                .then(res => {
                  // if ((res.StatusCode == "200" && res.Data == true) || sessionStorage.getItem('isManage') == '2') {
                  if (res.StatusCode == "200" && res.Data == true) {
                    getData('/api/common/system/list', {
                      sysIds: '210'
                    },
                    ).then((res) => {
                      return res.json();
                    }).then((json) => {
                      let data = json.data;
                      if (data.length > 0) {
                        // sessionStorage.setItem('previewIP', JSON.stringify(data[0]));
                        sessionStorage.setItem('PsnMgrLgAssistantAddr', data[0].webSvrAddr);
                        sessionStorage.setItem('PsnMgrToken', token);
                        sessionStorage.setItem('PsnMgrMainServerAddr', schoolData.baseUrl);
                        sessionStorage.setItem('PsnMgrLoading', 1);
                      } else {
                        // sessionStorage.setItem('previewIP', JSON.stringify({}));
                      }
                    })
                    // 获得当前学年学期信息
                    getData('/api/common/school/term/current/info', {
                      schoolId: userInfo.schoolId,
                    }).then(data => {
                      return data.json()
                    }).then(json => {
                      if (json.code == "200") {
                        let term = json.data;
                        // term.term = '2023-202402'
                        // term.termEndDate = '2024-08-01 00:00:00'
                        // term.termStartDate = '2024-03-01 00:00:00'
                        sessionStorage.setItem('termInfo', JSON.stringify(term));
                        //锁控校验
                        getData('/api/common/locker/check', {
                          sysId: this.state.sysId,
                          lockerId: this.state.lockerId,
                          productUseRange: schoolData.productUseRange,
                          schoolId: userInfo.schoolId,
                        }).then(data => {
                          return data.json()
                        }).then(json => {
                          if (json.code == "200" && json.data.result == '1') {
                            console.log('json.data', json.data);
                            if (Number(json.data.maxPoint) > 0) {
                              sessionStorage.setItem('StandardEdition', 1);
                            } else {
                              sessionStorage.setItem('StandardEdition', 0);
                            }
                            //获得历史学年学期信息
                            getData('/api/common/school/term/history', {
                              schoolId: userInfo.schoolId,
                            }).then(data => {
                              return data.json()
                            }).then(json => {
                              if (json.code == "200") {
                                console.log('json.data', json.data);
                                let data = json.data.concat([]);
                                data.forEach((term, index) => {
                                  let year = term.termInfo.slice(0, 4);
                                  let semester = term.termInfo.slice(9, 11);
                                  let text = `${year}-${parseInt(year) + 1}学年`;
                                  let value = parseInt(semester) - 1; // 因为value从0开始
                                  if (semester === '01') {
                                    text += '第1学期';
                                  } else if (semester === '02') {
                                    text += '第2学期';
                                  } else {
                                    text += `第${semester}学期`;
                                  }
                                  term.text = text;
                                  term.value = value;
                                  term.term = term.termInfo;
                                });
                                sessionStorage.setItem('termHistory', JSON.stringify(data));
                                this.setState({
                                  start: 1
                                })
                              }
                            });
                          }
                        });
                      }
                    });
                  } else {
                    this.alertAInfo2();
                  }
                })

            }

          })

      } else {
        let url = window.location.href;
        url = url.split('?');
        if (url.length > 1 && url[1].indexOf('&') > -1) {
          let pram = url[1].split('&');
          url = url[0] + '?';
          pram.map((item) => {
            if (item.indexOf('lg_tk=') === -1) {
              url += item + '&';
            }
          })
          url = url.slice(0, -1);
        } else {
          url = url[0];
        }
        if (url.slice(-2) == '#/') {
          url = url.slice(0, -2);
        }
        url = encodeURIComponent(url);
        sessionStorage.removeItem('token');
        window.open(sessionStorage.getItem('baseUrl') + '?lg_sysid=' + '252' + '&lg_preurl=' + url, '_self');
        console.log('请重新登录！');
      }
    })
  }
  render() {
    console.log("用户类型：", sessionStorage.getItem('UserType'), "比较结果:", sessionStorage.getItem('UserType') == 0)
    return (
      <div className="App">
        {this.state.start === 1 ? <div>
          <div>
            {/* <Search></Search> */}
            <Router>
              {/* exact表示绝对匹配 */}
              {/* 在react-router中每一个Route相当于一个组件 */}
              {/* 在传递参数的时候可以设置成 :参数名? 表示可选参数 */}
              {/* Switch表示只匹配一个符合条件的路由 */}
              <Switch>
                <Route path="/" exact component={DutyWeekCenter} />
                <Route path="/NoticeContent" component={NoticeDetails} />
                <Route path="/404" component={Logidn} />
                <Route path="/Error" component={Error} />
                <Route path="/ErrorTips" component={ErrorTips} />
              </Switch>
            </Router>
          </div>
        </div> : ''}
        <div className="example" style={{ display: 'none', height: document.documentElement.clientHeight + 'px', lineHeight: document.documentElement.clientHeight + 'px' }}> <Spin size="large" /></div>
      </div>
    );
  }
}
export default App;